package com.distribution.common.web.handler;

import com.distribution.common.web.response.ResponseResult;
import com.distribution.common.web.response.ResponseUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author test
 * @date 2022年01月04日 13:43
 */

@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException, ServletException {
        if(exception instanceof BadCredentialsException){
            ResponseUtils.send(httpServletResponse,new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"user name or password is wrong"));
        }

        ResponseUtils.send(httpServletResponse,new ResponseResult(HttpStatus.BAD_REQUEST.value(),"login failure"));
    }
}
